<!--
 * @Descripttion: 收发存汇总
 * @Author: xiaojia
 * @Date: 2020-11-27 16:36:27
-->
<template>
  <a-card :bordered="false" title>
    <div v-show="showSpin">
      <a-spin tip="正在导出..." size="large">
        <div class="spin-content"></div>
      </a-spin>
    </div>
    <!-- 顶部查询 -->
    <a-form-model :model="formdata" v-bind="layout">
      <a-row>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="仓库名称">
            <a-select v-model="formdata.pkStordoc" mode="multiple" allowClear>
              <a-select-option
                v-for="item in WarehouseCodeList"
                :key="item.depotId"
                :value="
                  item.depotNo + '|' + item.depotName + '|' + item.pkStordoc
                "
                >{{ item.depotNo }} {{ item.depotName }}</a-select-option
              >
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="存货分类">
            <a-tree-select
              showSearch
              v-model="formdata.sort"
              mode="multiple"
              :size="size"
              style="width: 100%"
              allow-clear
              :tree-data="inventoryNoList"
              @change="sortchangeSearch"
              onSelect
              tree-node-filter-prop="title"
              :replace-fields="replaceFields"
            >
            </a-tree-select>
          </a-form-model-item>
        </a-col>

        <a-col :md="8" :sm="24">
          <a-form-model-item label="收发类别">
            <a-select
              showSearch
              v-model="formdata.sendReceiveType"
              style="width: 100%"
              @change="shoufaleibieMethod"
            >
              <a-select-option
                v-for="(item, index) in shoufaleibieList"
                :key="index"
                :value="item.id + '|' + item.name"
                >{{ item.name }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
      </a-row>

      <a-row>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="存货名称">
            <a-select
              v-model="formdata.inventoryName"
              mode="multiple"
              :size="size"
              allowClear
              @search="handleSearch"
              @change="inventoryNameChange"
              showSearch
            >
              <a-select-option
                v-for="val in stockCodeList"
                :key="val.id"
                :value="
                  val.invcode +
                  '|' +
                  val.inventoryName +
                  '|' +
                  val.invspec +
                  '|' +
                  val.unit +
                  '|' +
                  val.pkInvbasdoc
                "
              >
                {{ val.invcode }} {{ val.inventoryName }}{{ val.invspec }}
              </a-select-option>
            </a-select>
          </a-form-model-item>
        </a-col>
        <a-col :md="8" :sm="24">
          <a-form-model-item label="会计日期">
            <a-range-picker
              format="YYYY-MM"
              @change="onChange"
              v-model="formdata.AccountingDate"
            />
          </a-form-model-item>
        </a-col>

        <a-col :md="8" :sm="24">
          <a-form-model-item label="业务日期">
            <!-- Business date -->
            <a-range-picker
              @change="onChange"
              v-model="formdata.BusinessDate"
            />
          </a-form-model-item>
        </a-col>
      </a-row>
      <a-row>
        <a-col :md="24" :sm="24" :style="{ textAlign: 'right' }">
          <a-button
            type="primary"
            style="margin-right: 8px"
            @click="onSubmit()"
          >
            查询
          </a-button>
          <a-button style="margin-right: 8px" @click="reset"> 重置 </a-button>
          <a-button style="margin-right: 8px" @click="exportToExcel()">
            导出
          </a-button>
        </a-col>
      </a-row>

      <br />
    </a-form-model>
    <!-- 列表显示 -->
    <a-form-model>
      <a-table
        :columns="columns"
        :data-source="dataSource"
        :pagination="pagination"
        @change="handleTableChange"
        :scroll="{ x: 3000, y: 670 }"
        id="myTable"
        size="small"
      >
        <!-- <span slot="action" slot-scope="text, record">
          <a @click="workupdate(record)" type="primary">
            编辑
          </a>
          <a-divider type="vertical" />
          <a-popconfirm
            ok-text="确定"
            cancel-text="取消"
            @confirm="workdelete(record)"
          >
            <template slot="title">
              <p>确定删除？</p>
            </template>
            <a type="danger"> 删除 </a>
          </a-popconfirm>
        </span> -->
      </a-table>
    </a-form-model>
  </a-card>
</template>
<script>
import moment from "moment";
import FileSaver from "file-saver";
import { sheet2blob } from "@/utils/export.js";
import XLSX from "xlsx";
import { ShouFaCunHuiZongHttp } from "../../services/modules/ChaXunYuTongJi/ShouFaCunHuiZong.js";
const $http = new ShouFaCunHuiZongHttp();
// import { ZiDianBiaoHttp } from "@/services/modules/ZiDianBiao.js";
// const zdbHttp = new ZiDianBiaoHttp(); // 字典表
import { CommonAjax } from "../../services/modules/common.js";
const comhttp = new CommonAjax();
export default {
  data() {
    return {
      showSpin: false, //打印加载中
      replaceFields: {
        children: "syncInventoryClassificationEntityList",
        title: "invclassname",
        value: "pkInvcl",
      },
      size: "default", //多选框的大小
      WarehouseCodeList: [], //仓库名称（多选）字典表
      inventoryNoList: [], //存货分类字典表
      stockCodeList: [], //存货名称字典表
      documentStatusList: [], //单据状态
      shoufaleibieList: [], //收发类别字典表
      no: 0,
      dataSource: [],
      //列表分页
      pagination: {
        total: 0,
        current: 1,
        pageSize: 10, //每页中显示10条数据
        pageSizeOptions: ["10"], //每页中显示的数据
        showTotal: (total) => `共有${total}条数据`, //分页中显示总的数据
      },
      queryParam: {
        //查询参数
        page: 1, //第几页
        size: 10, //每页中显示数据的条数
      },
      queryStr: "",

      //顶部查询条件
      formdata: {
        pkStordoc: [], //仓库名称
        sort: "", //存货分类
        sendReceiveType: "", //收发类别
        auditMark: "", //单据状态
        inventoryName: [], //存货编码
        BusinessDate: [], //业务日期
        AccountingDate: [], //会计日期
      },
      layout: {
        labelCol: { span: 8 }, //字
        wrapperCol: { span: 15 }, //框内大小
      },

      columns: [
        {
          title: "序号 ",

          dataIndex: "key",
          key: "0",
          align: "center",
        },
        {
          title: "仓库名称 ",
          dataIndex: "pkStordocName",
          key: "1",
          align: "center",
        },
        {
          title: "存货编码",
          dataIndex: "inventoryNo",
          key: "2",
          align: "center",
        },
        {
          title: "存货名称",
          dataIndex: "inventoryName",
          key: "3",
          align: "center",
        },

        {
          title: "规格型号",
          dataIndex: "specificationsModel",
          key: "4",
          align: "center",
        },

        {
          title: "单位",
          dataIndex: "unit",
          key: "5",
          align: "center",
        },

        {
          title: "期初数量",
          dataIndex: "balance",
          key: "6",
          align: "center",
        },
        {
          title: "期初金额",
          dataIndex: "openingAmount",
          key: "7",
          align: "center",
        },
        {
          title: "入库数量",
          dataIndex: "inQuantity",
          key: "8",
          align: "center",
        },
        {
          title: "入库金额",
          dataIndex: "inMoney",
          key: "9",
          align: "center",
        },
        {
          title: "出库数量",
          dataIndex: "outQuantity",
          key: "10",
          align: "center",
        },
        {
          title: "出库金额",
          dataIndex: "outMoney",
          key: "11",
          align: "center",
        },
        {
          title: "期末数量",
          dataIndex: "finalQuantity",
          key: "12",
          align: "center",
        },
        {
          title: "期末金额",
          dataIndex: "finalOpeningAmount",
          key: "13",
          align: "center",
        },
      ],
    };
  },
  computed: {},
  updated() {},
  methods: {
    handleSearch(value) {
      //模糊查询
      this.stockCodeList = [];
      console.log("value", value);
      let query = "?name=" + value;
      console.log("query", query);
      if (value == "" || value == null) {
        this.stockCodeList = [];
      } else {
        comhttp.getgetSearchInventoryInformationFile(query).then((res) => {
          console.log("结果为", res);
          // this.goodsList = res.result;
          for (let i = 0; i < res.result.length; i++) {
            if (
              res.result[i].specificationsModel == "null" ||
              res.result[i].specificationsModel == null
            ) {
              res.result[i].specificationsModel = "";
            }
            if (res.result[i].unit == "null" || res.result[i].unit == null) {
              res.result[i].unit = "";
            }
            let data = {
              key: i,
              inventoryId: res.result[i].id, // 存货 id
              invcode: res.result[i].invcode, //存货编码
              inventoryName: res.result[i].invname, //存货名称
              invspec: res.result[i].invspec, //规格型号
              unit: res.result[i].unit, //单位
              pkInvbasdoc: res.result[i].pkInvbasdoc,
            };
            this.stockCodeList.push(data);
          }
        });
      }
    },
    // 搜索栏选择存货编码编码的change触发函数
    inventoryNameChange(value, option) {
      console.log(value, option);
      this.formdata.id = option.key;
      // console.log(value , option);
      let invcodeArr = [];
      value.forEach((item) => {
        invcodeArr.push(item.split("|")[4]);
      });
      // const newValue = value.split("|");
      // console.log("搜索栏选择了存货编码", newValue);
      this.formdata.invcode = invcodeArr.join(","); // 存货名称主键
      // this.formdata.inventoryName = newValue[1];
      // this.formdata.inventoryInformationId = newValue[2];
    },
    getApplyStorage() {
      this.WarehouseCodeList = [];
      // 获取仓库名称
      comhttp.getAllNumberName_new_forU8c().then((res) => {
        console.log("获取所有仓库", res);
        for (let i = 0; i < res.result.length; i++) {
          let data = {
            id: res.result[i].pkStordoc,
            depotName: res.result[i].storname,
            depotNo: res.result[i].storcode,
            pkStordoc: res.result[i].pkStordoc,
          };
          this.WarehouseCodeList.push(data);
        }
        console.log("返回仓库编码、仓库名称", this.WarehouseCodeList);
      });
    },
    //获取存货分类字典表
    // getInventoryClassificationList() {
    //   console.log("123存货分类");

    //   zdbHttp.getInventoryClassificationList().then((res) => {
    //     console.log("存货分类字典表", res);
    //     this.inventoryNoList = res.result;
    //   });
    // },
    getInventoryClassificationList() {
      //获取存货分类
      this.treeDetilData = [];
      comhttp.GetSaveCargoClassification().then((res) => {
        console.log("存货分类！！！！！！！", res);
        this.inventoryNoList = res.result;
        this.disableParent(this.inventoryNoList);
      });
    },
    disableParent(Tree) {
      const setData = Tree.map((item) => {
        if (item.children && item.children.length) {
          item[`disabled`] = true;
          this.disableParent(item.children);
        }
        return item;
      });
      return setData;
    },
    //存货分类-搜索
    sortchangeSearch(value, option) {
      console.log("选择的存货分类是:", `selected ${value}`);
      this.formdata.sort = value;
      console.log(option, "11");
    },

    //收发类别列表
    shoufaleibieListmethod(queryPath = "") {
      console.log("hfougdiuy");
      comhttp.getReceiveSendTypeListAll(queryPath).then((res) => {
        console.log("收发类别列表", res);
        this.shoufaleibieList = res.result;
      });
    },
    //收发类别触发函数
    shoufaleibieMethod(value) {
      console.log("收发类别触发函数value", value);
      let array = value.split("|");
      console.log("array", array);
      console.log("array[0]", array[0]);
      console.log("array[1]", array[1]);
      // 表格自动填充所属单位
      this.formdata.sendReceiveTypeId = array[0]; //收发类别id
      this.formdata.sendReceiveType = array[1]; //收发类别name
    },

    //获取单据状态
    getAuditMarkAndDocumentStatus() {
      comhttp.getAuditMarkAndDocumentStatus().then((res) => {
        console.log("单据状态字典表", res);
        this.documentStatusList = res.result;
      });
    },
    //获取列表
    getlist() {
      const { current } = this.pagination; // 分页第一步：拿到要跳转的页数
      let query = `?pageNo=${current}&auditMark=1${this.queryStr}`;
      $http.shoufacunselect(query).then((res) => {
        console.log("获取列表", res);
        // 分页第二步：将服务七返回的分页数据存储到页面上
        this.pagination.current = res.result.pageNo;
        this.pagination.total = res.result.total;
        this.pagination.pageSize = res.result.pageSize;
        this.maxSize = res.result.total;
        // this.dataSource = ;
        let dataSource = [];
        const data = res.result.list;
        for (let i = 0; i < data.length; i++) {
          let itemData = {
            key: i + (current - 1) * res.result.pageSize + 1, // 分页3：修改数据序号
            pkStordocName: data[i].storname,
            inventoryNo: data[i].invcode,
            inventoryName: data[i].invname,
            specificationsModel: data[i].invspec,
            unit: data[i].measname,
            balance: data[i].balance,
            openingAmount: data[i].balanceAmount,
            inQuantity: data[i].inQuantity,
            inMoney: data[i].inMoney,
            outQuantity: data[i].outQuantity,
            outMoney: data[i].outMoney,
            finalQuantity: data[i].finalQuantity,
            finalOpeningAmount: data[i].finalOpeningAmount,
            pkInvbasdoc: data[i].pkInvbasdoc,
          };

          dataSource.push(itemData);
        }
        this.dataSource = dataSource;
        if (this.dataSource == undefined || this.dataSource.length <= 0) {
          this.$message.warning("暂无符合查询条件的数据");
        }
      });
    },
    //更改时间格式
    getBusinessDate() {
      if (this.formdata.BusinessDate[0]) {
        return `${moment(this.formdata.BusinessDate[0]).format("YYYY-MM-DD")}`;
      } else {
        return "";
      }
    },
    //更改时间格式
    getBusinessDate1() {
      if (this.formdata.BusinessDate[1]) {
        return `${moment(this.formdata.BusinessDate[1]).format("YYYY-MM-DD")}`;
      } else {
        return "";
      }
    },
    //更改时间格式
    getAccountingDate() {
      if (this.formdata.AccountingDate[0]) {
        return `${moment(this.formdata.AccountingDate[0]).format("YYYY-MM")}`;
      } else {
        return "";
      }
    },
    //更改时间格式
    getAccountingDate1() {
      if (this.formdata.AccountingDate[1]) {
        return `${moment(this.formdata.AccountingDate[1]).format("YYYY-MM")}`;
      } else {
        return "";
      }
    },
    //查询按钮
    onSubmit() {
      let formdata = this.formdata;
      console.log(formdata);
      let queryStr = "";

      // 仓库名称
      if (formdata.pkStordoc.length > 0) {
        queryStr += "&pkStordoc=";
        let pkStordoc = [];
        formdata.pkStordoc.forEach((item) => {
          const pkStordocItem = item.split("|")[2];
          pkStordoc.push(pkStordocItem);
        });
        queryStr += pkStordoc.join(",");
      }

      // 存货分类主键
      if (formdata.sort) {
        queryStr += `&pkInvcl=${formdata.sort}`;
      }

      // 收发类别
      if (formdata.sendReceiveType) {
        console.log(this.shoufaleibieList);
        let filter = this.shoufaleibieList.filter(
          (item) => item.name === formdata.sendReceiveType
        )[0];
        console.log(filter);
        queryStr += `&sendReceiveType=${filter.id}`;
      }

      // 存货名称
      if (formdata.invcode) {
        queryStr += `&pkInvbasdoc=${formdata.invcode}`;
      }

      // 会计日期（精确到月份）
      if (formdata.AccountingDate.length > 0) {
        queryStr += `&accountingPeriodBegin=${moment(
          formdata.AccountingDate[0]
        ).format("YYYY-MM")}`;
        queryStr += `&accountingPeriodEnd=${moment(
          formdata.AccountingDate[1]
        ).format("YYYY-MM")}`;
      }
      // 业务日期 （精确到天)
      if (formdata.BusinessDate.length > 0) {
        queryStr += `&beginDate=${moment(formdata.BusinessDate[0]).format(
          "YYYY-MM-DD"
        )}`;
        queryStr += `&endDate=${moment(formdata.BusinessDate[1]).format(
          "YYYY-MM-DD"
        )}`;
      }

      this.queryStr = queryStr;
      this.pagination.current = 1;
      this.getlist();
    },
    // 重置按钮
    reset() {
      this.formdata = {
        pkStordoc: [], //所属单位
        sort: "", //存货分类
        sendReceiveType: "", //收发类别
        auditMark: "", //单据状态
        inventoryName: [], //存货编码
        BusinessDate: [], //业务日期
        AccountingDate: [], //会计日期
      };
      this.queryStr = "";
      this.pagination.current = 1;
      this.getlist();
    },

    //弹出日历和关闭日历的回调
    onChange(date, dateString) {
      console.log(date, dateString);
    },
    // 分页4：拿到组件跳转的页数
    handleTableChange(pagination) {
      this.pagination.current = pagination.current;
      this.pagination.pageSize = pagination.pageSize;
      this.getlist();
    },

    // 导出
    exportToExcel() {
      this.showSpin = true; //打印加载中

      let query = `?pageNo=1&pageSize=${this.maxSize}&auditMark=1${this.queryStr}`;
      $http.shoufacunselect(query).then((res) => {
        console.log("获取列表", res);
        let array = res.result.list;
        this.exportBasic(array);
      });
    },
    //  接收数组，进行导出
    exportBasic(Array) {
      console.log("要导出的数据为:::::", Array);
      //  规整要导出的数据:::::
      let array = [];
      for (let i = 0; i < Array.length; i++) {
        let data = {
          序号: i + 1,
          仓库名称: Array[i].storname,
          存货编码: Array[i].invcode,
          存货名称: Array[i].invname,
          规格型号: Array[i].invspec,
          单位: Array[i].measname,
          期初数量: Array[i].balance,
          期初金额: Array[i].balanceAmount,
          入库数量: Array[i].inQuantity,
          入库金额: Array[i].inMoney,
          出库数量: Array[i].outQuantity,
          出库金额: Array[i].outMoney,
          期末数量: Array[i].finalQuantity,
          期末金额: Array[i].finalOpeningAmount,
        };
        array.push(data);
      }
      // 生成 sheet 表格 数据
      let sheet = XLSX.utils.json_to_sheet(array, {
        // 对导出内容进行相应的排序,手动排序。
        header: [
          "序号",
          "仓库名称",
          "存货编码",
          "存货名称",
          "规格型号",
          "单位",
          "期初数量",
          "期初金额",
          "入库数量",
          "入库金额",
          "出库数量",
          "出库金额",
          "期末数量",
          "期末金额",
        ],
      });
      // 生成导出表格
      let blob = sheet2blob(sheet);
      try {
        FileSaver.saveAs(
          new Blob([blob], {
            type: "application/octet-stream",
          }),
          "收发存汇总.xlsx" // 导出文件夹名称
        );
      } catch (e) {
        console.log(e);
      }
      this.showSpin = false; //导出中
    },
  },
  mounted() {
    this.getInventoryClassificationList(); //获取存货分类字典表
    this.getApplyStorage(); // 获取仓库编码、名称
    // this.getInventoryInformation(); //获取存货名称list
    this.shoufaleibieListmethod(); //收发类别字典表
    this.getAuditMarkAndDocumentStatus(); //单据状态字典表
    this.getlist(); //获取收发存列表
  },
};
</script>
